package com.simple.elpmobile.onlinecase.ui.base;


import com.simple.elpmobile.onlinecase.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.drawable.AnimationDrawable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class LoadingDialog {
	private ProgressDialog mProgressDialog = null;
	private Activity mActivity = null;
	private View loadingView = null;
	private AnimationDrawable loadingCircle = null;
	
	public LoadingDialog(Activity act) {
		mActivity = act;
		
	}

	// 弹出进度条对话框
	public void showDialog(String msg) {
		showDialog(msg,false);
	}

	public interface DialogDismissListener{
		public void onDismiss();
	}
	private DialogDismissListener listener;
	
	
	public void setListener(DialogDismissListener listener) {
		this.listener = listener;
	}

	// 弹出进度条对话框
	public void showDialog(String msg,boolean cancelAble) {
		if (mActivity == null)
			return;
		if (mProgressDialog == null) {
		    Context context = mActivity.getParent();
		    if ( null == context )
		        context = mActivity;
			mProgressDialog = new ProgressDialog(context,R.style.CustomProgressDialog);
			mProgressDialog.setCancelable(cancelAble);
			mProgressDialog.setCanceledOnTouchOutside(false);
		}
		
		
		mProgressDialog.show();
		
		
		loadingView = (View) LayoutInflater.from(mActivity).inflate(
				R.layout.big_loading, null);
		TextView text = (TextView)loadingView.findViewById(R.id.loading_text);
		text.setText(msg);
		
		mProgressDialog.setContentView(loadingView);
		
		loadingCircle = (AnimationDrawable) ((ImageView) loadingView
				.findViewById(R.id.big_circle)).getBackground();
		loadingView.post(new Runnable() {
			public void run() {
				loadingCircle.start();
			}
		});
		mProgressDialog.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if(listener!=null && keyCode == KeyEvent.KEYCODE_BACK){
					listener.onDismiss();
				}
				return false;
			}
		});
	}
	
	public void dismissDialog() {
		if (mActivity != null && !mActivity.isFinishing()) {
			if (mProgressDialog != null && mProgressDialog.isShowing()) {
				loadingCircle.stop();
				mProgressDialog.dismiss();
				mProgressDialog = null;
			}
		}
	}
		
}
